from django_redis import get_redis_connection
from rest_framework import serializers
from .models import User
import re


class UserModelSerializer(serializers.ModelSerializer):
    """用户序列化器"""
    sms = serializers.CharField(write_only=True, max_length=6,min_length=4,help_text="短信验证码")
    token = serializers.CharField(read_only=True, min_length=1, help_text="jwt")

    class Meta:
        model = User
        fields = ["id","username","password","token","mobile","sms"]
        # 字段的额外声明
        extra_kwargs = {
            "id": {"read_only":True,},
            "username": {"read_only":True,},
            "password": {"write_only":True,"min_length": 6},
            "mobile": {"write_only": True,"min_length": 11},
        }

    def validate(self, attrs):
        mobile = attrs.get("mobile")
        ret = re.match(r"1[3-9]\d{9}$", mobile)
        if not ret:
            raise serializers.ValidationError("对不起，手机格式错误！")
        try:
            User.objects.get(mobile=mobile)
            raise serializers.ValidationError("对不起，当前手机号以及被注册！")
        except User.DoesNotExist:
            pass

        #  验证短信是否正确
        user_sms = attrs.get("sms")
        redis_conn = get_redis_connection("sms_code")
        redis_sms = redis_conn.get("sms_%s" % mobile)
        if redis_sms is None:
            raise serializers.ValidationError("对不起，验证码已过期！")
        
        if redis_sms.decode() != user_sms:
            raise serializers.ValidationError("对不起，验证码错误！")
        
        return attrs

    def create(self, validated_data):
        mobile = validated_data.get("mobile")
        password = validated_data.get("password")
        username = mobile
        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
            # 注册用户成功以后，redis中的短信相关数据
            redis_conn = get_redis_connection("sms_code")
            pipe = redis_conn.pipeline()
            pipe.multi()
            pipe.delete("sms_%s" % mobile)
            pipe.delete("send_%s" % mobile)
            pipe.execute()
        except:
            raise serializers.ValidationError("创建用户失败！")

        # 手动生成jwt
        from rest_framework_jwt.settings import api_settings
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        user.token = jwt_encode_handler(payload)

        return user